'use client'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from '@/components/ui/dialog'
import { useEffect } from 'react'
import { useCategoriesStore } from '../_libs/use-category-store'
import { Button } from '@/components/ui/button'
import { Plus } from 'lucide-react'
import { useForm, Controller, SubmitHandler } from 'react-hook-form'
import { Input } from '@/components/ui/input'
import { useCreateCategory, useUpdateCategory } from '../_services/use-category-mutations'
import { CategorySchema, categoryDefaultValues } from '../_types/categorySchema'
import { useCategory } from '../_services/use-category-queries'
const CategoryFormDialog = () => {
  const { selectedCategoryId, categoryDialogOpen, updateCategoryDialogOpen } = useCategoriesStore()

  const { handleSubmit, control, reset } = useForm<CategorySchema>({
    defaultValues: categoryDefaultValues
  })
  const handleSuccess = () => {
    handleDialogOpenChange(false)
  }

  const handleDialogOpenChange = (open: boolean) => {
    updateCategoryDialogOpen(open)
    if (!open) reset(categoryDefaultValues)
  }
  const onSubmit: SubmitHandler<CategorySchema> = data => {
    if (data.action === 'create') {
      createCategoryMutation.mutate(data, {
        onSuccess: handleSuccess
      })
    } else {
      updateCategoryMutation.mutate(data, {
        onSuccess: handleSuccess
      })
    }
  }

  const categoryQuery = useCategory()
  const createCategoryMutation = useCreateCategory()
  const updateCategoryMutation = useUpdateCategory()
  useEffect(() => {
    if (categoryQuery.data) reset(categoryQuery.data as CategorySchema)
  }, [categoryQuery.data, reset, selectedCategoryId])

  return (
    <Dialog open={categoryDialogOpen} onOpenChange={handleDialogOpenChange}>
      <DialogTrigger asChild>
        <Button>
          <Plus className='mr-2' />
          添加分类
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>新增分类</DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit(onSubmit)} className='space-y-6'>
          <div className='grid grid-cols-2 gap-4'>
            <div className='col-span-2'>
              <Controller
                rules={{ required: true }}
                name='name'
                control={control}
                render={({ field }) => <Input {...field} autoComplete='off' />}
              />
            </div>
          </div>
          <DialogFooter>
            <Button type='submit' isLoading={createCategoryMutation.isPending}>
              {!!selectedCategoryId ? '编辑' : '新增'}分类
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}

export { CategoryFormDialog }
